import axios from 'axios'

// API基础配置
// const API_BASE_URL = 'http://localhost:3002/questionChat'
const API_BASE_URL = 'https://iiyunsheng.tech/questionChat'  // 生产环境

const api = axios.create({
  baseURL: `${API_BASE_URL}/api`,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})


// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API Error:', error)
    return Promise.reject(error)
  }
)

// 定义API响应类型
interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  token?: string
}

// 用户相关API
export const userApi = {
  // 注册
  register: (userData: {
    username: string
    password: string
    real_name: string
    age: number
    gender: string
  }): Promise<ApiResponse> => api.post('/register', userData),
  
  // 登录
  login: (username: string, password: string): Promise<ApiResponse> => 
    api.post('/login', { username, password }),
  
  // 获取用户信息
  getUserInfo: (id: number): Promise<ApiResponse> => api.get(`/users/${id}`),
  
  // 获取用户列表
  getUsers: (): Promise<ApiResponse> => api.get('/users'),
  
  // 更新用户进度
  updateUserProgress: (id: number, allow_node: number): Promise<ApiResponse> =>
    api.put(`/users/${id}/progress`, { allow_node }),
  
  // 更新用户记录位置
  updateRememberPosition: (id: number, node: number, num: number): Promise<ApiResponse> =>
    api.put(`/users/${id}/remember-position`, { node, num }),
  
  // 获取用户记录位置
  getRememberPosition: (id: number): Promise<ApiResponse> =>
    api.get(`/users/${id}/remember-position`),
  
  // 删除用户
  deleteUser: (id: number): Promise<ApiResponse> => api.delete(`/users/${id}`)
}

// 脚本相关API
export const scriptApi = {
  // 获取章节脚本
  getChapterScripts: (nodenum: number): Promise<ApiResponse> => 
    api.get(`/scripts/${nodenum}`),
  
  // 获取所有脚本
  getAllScripts: (): Promise<ApiResponse> => api.get('/scripts'),
  
  // 创建脚本
  createScript: (data: any): Promise<ApiResponse> => api.post('/scripts', data),
  
  // 更新脚本
  updateScript: (id: number, data: any): Promise<ApiResponse> => 
    api.put(`/scripts/${id}`, data),
  
  // 删除脚本
  deleteScript: (id: number): Promise<ApiResponse> => api.delete(`/scripts/${id}`),
  
  // 获取脚本文本内容（前端实现打字机效果）
  getScriptText: (scriptId: number): Promise<ApiResponse<{ content: string, length: number }>> => 
    api.get(`/script-text/${scriptId}`)
}

// 章节相关API
export const chapterApi = {
  // 获取所有章节信息
  getChapters: (): Promise<ApiResponse> => api.get('/chapters')
}


// 数据处理API
export const dataApi = {
  // 导入Excel
  importExcel: (formData: FormData): Promise<ApiResponse> => 
    api.post('/import-excel', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    }),
  
  // 导出Excel
  exportExcel: (nodenum?: number) => {
    const params = nodenum !== undefined ? { nodenum } : {}
    return axios.get(`${api.defaults.baseURL}/export-excel`, {
      params,
      responseType: 'blob'
    })
  },
  
  // 清除所有脚本数据
  clearAllScripts: (): Promise<ApiResponse> => api.delete('/clear-scripts'),
  
  // 获取上传地址
  getUploadUrl: (): string => `${api.defaults.baseURL}/import-excel`,
  
  // 健康检查
  healthCheck: (): Promise<ApiResponse> => api.get('/health')
}

export default api
